package com.xm9m.web.service.api;

import com.salesmanager.core.business.customer.model.Customer;
import com.salesmanager.core.business.customer.model.CustomerAuths;
import com.salesmanager.core.business.customer.service.CustomerService;
import com.salesmanager.core.business.generic.exception.ServiceException;
import com.salesmanager.core.modules.sms.SmsService;
import com.salesmanager.web.entity.SMSMessage;
import com.salesmanager.web.entity.SMSType;
import com.salesmanager.web.utils.SMS.ValidateCode;
import com.xm9m.web.service.api.request.BindMobilePostRequest;
import com.xm9m.web.service.constants.StatusCode;
import com.xm9m.web.service.entity.security.SecurityCustomer;
import com.xm9m.web.service.interfaces.AbstractRestApi;
import com.xm9m.web.service.interfaces.IXm9mResponse;
import com.xm9m.web.service.internal.util.BuildResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * Created by Liutong on 2016/6/18.
 */
public class BindMobilePost extends AbstractRestApi {

    @Autowired
    private SmsService smsService;

    @Autowired
    private CustomerService customerService;

    @Override
    public <T extends IXm9mResponse> T execute(String requestData, String version) throws Exception {

        BindMobilePostRequest request = super.json2Bean(requestData, BindMobilePostRequest.class);
        if (request == null) {
            return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.PARAM_WRONG);
        }

        Long customerId = super.getUserId();
       /* Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            SecurityCustomer userDetails = (SecurityCustomer) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            customerId = userDetails.getCustomerId();
        }
*/
        Map<String, Object> map;
        SMSMessage originMessage = (SMSMessage) smsService.getByTelephone(request.getMobile());
        SMSMessage newMessage = new SMSMessage();
        newMessage.setCode(request.getCaptcha());
        newMessage.setPhone(request.getMobile());
        newMessage.setType(SMSType.TELEPHONE_BIND.getValue());
        map = ValidateCode.validate(originMessage, newMessage);

        String valid = (String) map.get("valid");
        if ("false".equals(valid)) {
            return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.CAPTCHA_ERROR);
        }

        Customer customer = customerService.getById(customerId);
        Set<CustomerAuths> auths = customer.getAuths();
        CustomerAuths customerAuth = new CustomerAuths();
        customerAuth.setIdentifier(request.getMobile());
        customerAuth.setCreateTime(new Date());
        customerAuth.setIdentityType(1);
        customerAuth.setCertificate(request.getPassword());
        customerAuth.setStatus(1);
        customerAuth.setCustomer(customer);
        auths.add(customerAuth);

        customer.setAuths(auths);
        customer.setTelphone(request.getMobile());

        try {
            customerService.update(customer);
            return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.SUCCESS);
        } catch (ServiceException e) {
            e.printStackTrace();
            return (T) BuildResponseUtil.buildSimpleResponse(StatusCode.UNKNOWN_ERROR);
        }
    }
}
